<template>
  <el-dialog
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    :title="title"
    width="900px"
    @close="handleCancel">
    <div class="add-header">
      <el-button type="primary" @click="relativeInfosClick">
        {{ $t('crm.components.09869d99264e99e4a56b089f5aea021c') }}
      </el-button>
    </div>
    <div class="add-wrap">
      <el-form ref="ruleForm" :model="ruleForm">
        <el-table
          :key="refreshKey"
          height="350px"
          :data="tableData"
          :span-method="objectSpanMethod"
          border>
          <el-table-column
            prop="productName"
            width="120"
            :label="$t('crm.components.ff6d39f521918672027835d2b556892b')" />
          <el-table-column
            prop="productCategoryName"
            width="100"
            :label="$t('crm.components.8b4271b4a8347d4e59382c1452ec167c')" />
          <el-table-column
            prop="price"
            width="100"
            :label="`${$t('crm.components.5d47d90545804c3d8233ecedc9c749e2')}(${$unit('crm')})`"
            :formatter="fieldFormatter" />
          <el-table-column
            prop="desc"
            width="250"
            label="分成依据类型/比例">
            <template slot-scope="{row, $index}">
              <flexbox>
                <el-form-item
                  :prop="`tableData[${$index}].desc`"
                  :rules="getDescRule(row)">
                  <el-input
                    v-model="tableData[$index].desc"
                    maxlength="20"
                    placeholder="分成依据类型"
                  />
                </el-form-item>
                <el-form-item
                  style="margin-left: 8px;"
                  :prop="`tableData[${$index}].descRate`"
                  :rules="getDescRateRule(row)">
                  <el-input-number
                    v-model="tableData[$index].descRate"
                    style="width: 80px;"
                    :min="0"
                    :max="100"
                    :controls="false"
                    :precision="2"
                  />
                </el-form-item>
              </flexbox>
            </template>
          </el-table-column>
          <el-table-column
            prop="rate"
            width="320"
            label="分成人员/比例">
            <template slot-scope="{row, $index}">
              <flexbox
                v-for="(child, childIndex) in row.rateList"
                :key="childIndex"
                class="sub-cell">
                <el-form-item
                  class="is-fill"
                  :prop="`tableData[${$index}].rateList[${childIndex}].userId`"
                  :rules="getUserRule(row, child, childIndex)">
                  <wk-user-select
                    v-model="row.rateList[childIndex].userId"
                    style="width: 100%;"
                    :options="userList"
                    :props="{ isList: true }"
                    radio />
                </el-form-item>

                <el-form-item
                  :prop="`tableData[${$index}].rateList[${childIndex}].rate`"
                  :rules="getPercentRule(row, childIndex)">
                  <el-input-number
                    v-model="row.rateList[childIndex].rate"
                    style="width: 80px;"
                    :min="0"
                    :max="100"
                    :controls="false"
                    :precision="2"
                  />
                </el-form-item>
                <el-button
                  icon="wk wk-icon-create"
                  type="text"
                  @click="subItemClick('add',row,childIndex )" />
                <el-button
                  icon="wk wk-delete"
                  type="text"
                  @click="subItemClick('delete',row,childIndex )" />
              </flexbox>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$t('crm.components.d8e2b2f3f2aa2dc2811c9d05623f077b')"
            fixed="right">
            <template slot-scope="{ row ,$index }">
              <el-button
                icon="wk wk-icon-create"
                type="text"
                @click="itemHandleClick('add',row,$index )" />
              <el-button
                icon="wk wk-delete"
                type="text"
                @click="itemHandleClick('delete',row,$index )" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button v-debounce="handleConfirm" type="primary">
        {{ $t('crm.components.75758508749f8f0f94bacf2422b9fa09') }}
      </el-button>
      <el-button @click.native="handleCancel">
        {{ $t('crm.components.83f2ec0fa3b654bf884f8e6ae60831ac') }}
      </el-button>
    </span>

    <!-- 关联产品 -->
    <crm-relative
      v-if="relativeShow"
      ref="crmrelative"
      :visible.sync="relativeShow"
      :radio="false"
      :selected-data="selectedData"
      data-type="product"
      @changeCheckout="relativeInfosChange" />
  </el-dialog>
</template>

<script>
import {
  crmCustomerAddOrUpdateTeamProductAPI
} from '@/api/crm/customer'
import {
  crmBusinessAddOrUpdateTeamProductAPI
} from '@/api/crm/business'
import {
  crmContractAddOrUpdateTeamProductAPI
} from '@/api/crm/contract'
import {
  crmContactsAddOrUpdateTeamProductAPI
} from '@/api/crm/contacts'
import {
  crmReceivablesAddOrUpdateTeamProductAPI
} from '@/api/crm/receivables'
import {
  crmReturnVisitAddOrUpdateTeamProductAPI
} from '@/api/crm/visit'

import WkUserSelect from '@/components/NewCom/WkUserSelect'

import NP from 'number-precision'
import { objDeepCopy } from '@/utils'
import { separator } from '@/filters/vueNumeralFilter/filters'

export default {
  // CrossSellProductsAdd
  name: 'CrossSellProductsAdd',

  components: {
    WkUserSelect,
    CrmRelative: () =>
      import('@/components/CreateCom/CrmRelative')
  },

  props: {
    visible: {
      type: Boolean,
      required: true,
      default: false
    },
    userList: {
      type: Array,
      default: () => []
    },
    // 模块ID
    id: [String, Number],
    // 没有值就是全部类型 有值就是当个类型
    crmType: {
      type: String,
      default: ''
    },
    editList: Array // 编辑数据
  },

  data() {
    return {
      refreshKey: Date.now(),
      tableData: [],
      // 关联产品
      relativeShow: false
    }
  },

  computed: {
    title() {
      return this.editList ? this.$t('crm.components.2e0b225963d3f94d31a409c932d45fb0') : this.$t('crm.components.6fe80f555f126ad0b986f6940c6225bd')
    },

    ruleForm() {
      return { tableData: this.tableData }
    },

    selectedData() {
      const selected = []
      this.tableData.forEach(item => {
        const selectedIds = selected.map(o => o.productId)
        if (!selectedIds.includes(item.productId)) {
          selected.push(item)
        }
      })
      return { product: selected }
    }
  },

  watch: {},

  created() {
    if (this.editList) {
      const tableData = []
      const idObj = {
        productId: '',
        desc: ''
      }
      this.editList.forEach(item => {
        if (idObj.productId !== item.productId || idObj.desc !== item.desc) {
          idObj.productId = item.productId
          idObj.desc = item.desc
          const newItem = {
            ...item,
            rateList: [{
              rate: item.rate,
              userId: item.userId,
              tempId: item.id
            }],
            rowspan: 0,
            colspan: 0
          }
          delete newItem.id
          tableData.push(newItem)
        } else if (tableData.length > 0) {
          const lastItem = tableData[tableData.length - 1]
          lastItem.rateList.push({
            rate: item.rate,
            userId: item.userId,
            tempId: item.id
          })
        }
      })
      this.tableData = tableData

      this.handleItemTableSpan()
    }
  },

  mounted() {},

  beforeDestroy() {},

  methods: {
    userChange(val) {
      console.log('vvvvvvvvvvv')
      console.log(val)
    },
    /**
     * @description: 获取用户规则
     * @param {*} row
     * @return {*}
     */
    getUserRule(row, child, childIndex) {
      return [{ required: true, message: this.$t('crm.components.3118b4d33a9e14fc1f37127d35562921'), trigger: 'change' },
        {
          validator: ({ item }, value, callback) => {
            const { productId } = item
            const result = this.tableData.filter(o => o.productId === productId).map(o => o.rateList).flat()

            const userIdLength = result.filter(o => o.userId == child.userId).length
            userIdLength > 1 ? callback(new Error('同一产品选择的员工不能相同')) : callback()
          },
          item: row,
          trigger: ['change'] }]
    },

    /**
     * @description: 获取分成规则
     * @param {*} row
     * @return {*}
     */
    getDescRule(row) {
      return [{ required: true, message: '请输入', trigger: 'change' },
        {
          validator: ({ item }, value, callback) => {
            const descs = this.tableData.slice(item.start, item.end).filter(o => o.index !== item.index).map(item => item.desc)
            descs.includes(item.desc) ? callback(new Error('分成依据类型不能相同')) : callback()
          },
          item: row,
          trigger: ['change'] }]
    },

    /**
     * @description: 获取分成依据类型百分比规则
     * @param {*} row
     * @return {*}
     */
    getDescRateRule(row) {
      return {
        validator: ({ item }, value, callback) => {
          const { productId } = item
          let rate = 0
          this.tableData.forEach(item => {
            if (item.productId == productId) {
              rate = NP.plus(rate, item.descRate)
            }
          })
          rate !== 100 ? callback(new Error('同类型分成依据比例之和需为100%')) : callback()
        },
        item: row,
        trigger: ['change', 'blur']
      }
    },

    /**
     * @description: 获取百分比规则
     * @param {*} row
     * @return {*}
     */
    getPercentRule(row, index) {
      return {
        validator: ({ item }, value, callback) => {
          // const rangeItems = this.tableData.slice(item.start, item.end)
          let rate = 0
          item.rateList.forEach(o => {
            rate = NP.plus(rate, o.rate)
          })
          rate !== 100 ? callback(new Error('同类型比例之和需为100%')) : callback()
        },
        item: row,
        trigger: ['change', 'blur'] }
    },

    /**
     * @description: 选择产品
     * @return {*}
     */
    relativeInfosClick() {
      this.relativeShow = true
    },

    /**
     * @description: 产品选择
     * @return {*}
     */
    relativeInfosChange(res) {
      const data = res.data || []
      const productIds = this.tableData.map(item => item.productId)
      data.forEach(item => {
        if (!productIds.includes(item.productId)) {
          this.tableData.push({
            productName: item.name,
            productCategoryName: item.categoryName,
            price: item.price,
            productId: item.productId,
            desc: '',
            descRate: 0,
            rateList: [{
              rate: 0,
              userId: '' // 分成依据
            }],
            rowspan: 0,
            colspan: 0
          })
        }
      })

      this.handleItemTableSpan()
    },

    /**
     * @description: 标记数据中的合并信息
     * @return {*}
     */
    handleItemTableSpan() {
      const spanObj = {}
      let productId = ''
      let spanIndex = 1
      this.tableData.forEach((item, index) => {
        if (item.productId !== productId) {
          productId = item.productId
          spanIndex = index
          spanObj[spanIndex] = 1
        } else {
          spanObj[spanIndex]++
        }
      })

      let preItem = null

      this.tableData.forEach((item, index) => {
        const span = spanObj[index]
        item.index = index
        if (span !== undefined) {
          item.rowspan = span
          item.colspan = 1
          item.start = index
          item.end = index + span
          preItem = item
        } else {
          item.rowspan = 0
          item.colspan = 0
          if (preItem) {
            item.start = preItem.start
            item.end = preItem.end
          }
        }
      })
    },

    /**
     * 标签列表小项操作
     */
    subItemClick(type, item, index) {
      if (type === 'add') {
        item.rateList.splice(index + 1, 0, {
          rate: 0,
          userId: ''
        })
      } else if (type === 'delete') {
        item.rateList.splice(index, 1)
      }

      this.refreshKey = Date.now()
    },

    /**
     * 标签列表操作
     */
    itemHandleClick(type, item, index) {
      if (type === 'add') {
        const addItem = objDeepCopy(item)
        addItem.desc = ''
        addItem.rateList = [{
          userId: '',
          rate: 0
        }]
        this.tableData.splice(index + 1, 0, addItem)
        this.handleItemTableSpan()
      } else if (type === 'delete') {
        this.tableData.splice(index, 1)
        this.handleItemTableSpan()
      }
    },

    /**
     * @description: 合并单元格
     * @param {*} row
     * @param {*} column
     * @param {*} rowIndex
     * @param {*} columnIndex
     * @return {*}
     */
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex <= 2) {
        if (rowIndex % 2 === 0) {
          return row
        } else {
          return row
        }
      }
    },

    /**
     * 提交按钮
     */
    handleConfirm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const request = {
            customer: crmCustomerAddOrUpdateTeamProductAPI,
            business: crmBusinessAddOrUpdateTeamProductAPI,
            contract: crmContractAddOrUpdateTeamProductAPI,
            contacts: crmContactsAddOrUpdateTeamProductAPI,
            receivables: crmReceivablesAddOrUpdateTeamProductAPI,
            visit: crmReturnVisitAddOrUpdateTeamProductAPI
          }[this.crmType]
          const entity = []
          this.tableData.forEach(bigItem => {
            bigItem.rateList.forEach((item, index) => {
              const newItem = {
                ...bigItem,
                ...item
              }
              if (item.tempId) {
                newItem.id = item.tempId
                delete item.tempId
              }
              delete newItem.rateList
              entity.push(newItem)
            })
          })
          request({
            id: this.id,
            entity
          }).then(res => {
            this.$message.success(this.$t('crm.components.9083dc6d8e9f81eabf12b18388f0c93e'))
            this.$emit('success')
            this.handleCancel()
          }).catch(() => {})
        } else {
          return false
        }
      })
    },

    /**
     * 格式化字段
     */
    fieldFormatter(row, column) {
      // 如果需要格式化
      if (column.property == 'price') {
        return separator(this.$money('crm', row[column.property] || 0))
      }
      return row[column.property] === '' || row[column.property] === null ? '--' : row[column.property]
    },

    /**
     * 取消选择
     */
    handleCancel() {
      // custom-class="no-padding-dialog"
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 0 20px;
}

.add-header {
  line-height: 30px;
  text-align: right;
}

.add-wrap {
  .el-table {
    width: 100%;
    margin-top: 16px;
  }

  ::v-deep .el-input-number {
    width: 100%;

    .el-input__inner {
      padding: 0 6px !important;
      text-align: left;
    }
  }

  .el-form-item {
    margin-bottom: 0;
  }

  ::v-deep .el-form-item__content {
    line-height: 32px;
  }

  ::v-deep .el-form-item__error {
    padding-top: 0;
  }

  ::v-deep .el-table {
    .cell {
      padding-bottom: 4px;
      overflow: visible;
    }
  }

  .sub-cell {
    .el-form-item + .el-form-item {
      margin-left: 8px;
    }

    .is-fill {
      flex: 1;
    }
  }

  .sub-cell + .sub-cell {
    margin-top: 14px;
  }
}
</style>
